//
//  SRSetViewController.m
//  SportRing
//
//  Created by 微他 on 15-1-20.
//  Copyright (c) 2015年 HotOne. All rights reserved.
//

#import "SRSetViewController.h"
#import "Utils.h"
#import "SRViewSetting.h"
#import "SRTaskService.h"
#import "SRManager.h"
#import "SRDB.h"

@interface SRSetViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIAlertViewDelegate>
{
    UITableView *_tableView;
    NSArray *_arr;
    SRMe *_me;
    UITextField *_textField1;
    UITextField *_textField2;
    UILabel *_label1;
    UILabel *_label2;
    
    NSArray *_arr2; //包含了久坐提醒的时间
    NSString *_sitTooLong;
    
    UIButton *_button4;
    
    UIView *_spaceView;
    
}
@end

@implementation SRSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _me = [SRMe currentUser];
    self.navigationItem.hidesBackButton = YES;
    [self setCustomTitle:NSLocalizedString(@"设置", nil)];
    [self addBackButton];
    _arr = @[@[@"我的手环",@"每日目标"],@[@"来电提醒",@"久坐提醒",@"智能闹钟",@"我要吐槽",@"关于"]];
    _arr2 = @[@"每60分钟提醒",@"每45分钟提醒",@"每30分钟提醒",@"取消"];
    _sitTooLong = _arr2[0];
    
    
    [self initView];
}

- (void)buttonClick:(UIButton *)sender
{
    if (![sender.titleLabel.text isEqualToString:@"取消"]) {
        _sitTooLong = sender.titleLabel.text;
        [_tableView reloadData];
    }
    [self sitTooLongOptionsDisappear];
}

- (void)sitTooLongOptionsDisappear
{
    _black.alpha = 0;
    _spaceView.alpha = 0;
    _button4.alpha = 0;
}
- (void)sitTooLongOptionsAppear
{
    [UIView animateWithDuration:0.3 animations:^{
        _black.alpha = 0.6;
        _spaceView.alpha = 1;
        _button4.alpha = 1;
    }];
}

- (void)initView
{
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 100)];
    view.backgroundColor = [UIColor clearColor];
    _tableView.tableFooterView = view;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"退出登录" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
    button.backgroundColor = [UIColor colorWithRed:144.0/255.0 green:87.0/255.0 blue:192.0/255.0 alpha:1];
    button.layer.cornerRadius = 6;
    button.frame = CGRectMake(15, 40, CGRectGetWidth(self.view.bounds) - 30, 40);
    [button addTarget:self action:@selector(exitLogin) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    _textField1 = [[UITextField alloc] initWithFrame:CGRectMake(20, 5, 200, 20)];
    _textField1.hidden = YES;
    [self.view addSubview:_textField1];
    //添加toolbar适配键盘
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(20, 0, 320, 80)];
    topView.backgroundColor = [SetFontColorProperty setFontColor:241 float2:241 float3:241];
    _textField2 = [[UITextField alloc] initWithFrame:CGRectMake(20, 5, 230, 30)];
    _textField2.layer.cornerRadius = 4;
    _textField2.backgroundColor = [UIColor whiteColor];
    _textField2.delegate = self;
    _textField2.keyboardType = UIKeyboardTypeNumberPad;
    SRCurrentTask * task = [SRCurrentTask findCurrentTaskCINEForMe:[SRMe currentUser]];
    _textField2.text = [NSString stringWithFormat:@"%@",task.target];
    _textField2.returnKeyType = UIReturnKeyDone;
    [topView addSubview:_textField2];
    
    UIButton * doneButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [doneButton addTarget:self action:@selector(dismissKeyBoard) forControlEvents:UIControlEventTouchUpInside];
    doneButton.frame = CGRectMake(CGRectGetMaxX(_textField2.frame) + 10, 5, 50, 30);
    doneButton.backgroundColor = [UIColor colorWithRed:144.0/255.0 green:87.0/255.0 blue:192.0/255.0 alpha:1];
    doneButton.layer.cornerRadius = 4;
    [doneButton setTitle:NSLocalizedString(@"确认", nil) forState:UIControlStateNormal];
    [doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [topView addSubview:doneButton];
    
    UIView *spcaeview = [[UIView alloc] initWithFrame:CGRectMake(0, 40, CGRectGetWidth(topView.bounds), 40)];
    spcaeview.backgroundColor = [UIColor whiteColor];
    [topView addSubview:spcaeview];
    
    _label1 = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(_textField2.frame), 0, 100, 40)];
    [_label1 setFont:[UIFont systemFontOfSize:14]];
    [spcaeview addSubview:_label1];
    
    _label2 = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_label1.frame), 0, 100, 40)];
    [_label2 setFont:[UIFont systemFontOfSize:14]];
    [spcaeview addSubview:_label2];
    
    [_textField1 setInputAccessoryView:topView];
    
    /**********2015-4-23添加的设置页面的久坐提醒功能**************/
    
    _black = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    _black.backgroundColor = [UIColor blackColor];
    _black.alpha = 0;
    _black.tag = 699;
    [self.view addSubview:_black];
    
    _spaceView = [[UIView alloc] initWithFrame:CGRectMake(10, CGRectGetHeight(self.view.bounds) - 230, CGRectGetWidth(_black.bounds) - 20, 150)];
    _spaceView.backgroundColor = [UIColor whiteColor];
    _spaceView.tag = 700;
    _spaceView.layer.cornerRadius = 6;
    _spaceView.alpha = 0;
    [self.view addSubview:_spaceView];
    
    
    /*空白板按钮1*/
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button1 setTitle:_arr2[0] forState:UIControlStateNormal];
    button1.frame = CGRectMake(0, 0, CGRectGetWidth(_spaceView.frame), 50);
    [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button1.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [button1 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_spaceView addSubview:button1];
    
    
    /*灰色线1*/
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(0, 50, CGRectGetWidth(_spaceView.frame), 0.5)];
    line1.backgroundColor = [UIColor lightGrayColor];
    [_spaceView addSubview:line1];
    
    /*空白板按钮2*/
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button2 setTitle:_arr2[1] forState:UIControlStateNormal];
    button2.frame = CGRectMake(0, 50, CGRectGetWidth(_spaceView.frame), 50);
    [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button2.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [button2 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_spaceView addSubview:button2];
    
    
    /*灰色线2*/
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, 100, CGRectGetWidth(_spaceView.frame), 0.5)];
    line2.backgroundColor = [UIColor lightGrayColor];
    [_spaceView addSubview:line2];
    
    
    /*空白板按钮3*/
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button3 setTitle:_arr2[2] forState:UIControlStateNormal];
    button3.frame = CGRectMake(0, 100, CGRectGetWidth(_spaceView.frame), 50);
    [button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button3.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [button3 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_spaceView addSubview:button3];
    
    /*最下面按钮*/
    _button4 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [_button4 setTitle:_arr2[3] forState:UIControlStateNormal];
    _button4.frame = CGRectMake(10, CGRectGetMaxY(_spaceView.frame)+10, CGRectGetWidth(_spaceView.frame), 50);
    [_button4 setTitleColor:[UIColor colorWithRed:144.0/255.0 green:87.0/255.0 blue:192.0/255.0 alpha:1] forState:UIControlStateNormal];
    _button4.backgroundColor = [UIColor whiteColor];
    _button4.layer.cornerRadius = 6;
    [_button4.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [_button4 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    _button4.alpha = 0;
    [self.view addSubview:_button4];
    
}

- (void)dismissKeyBoard
{
    SRCurrentTask * task = [SRCurrentTask findCurrentTaskCINEForMe:[SRMe currentUser]];
    [task configAttributesWithBlock:^(SRCurrentTask *aSelf) {
        aSelf.target = @([_textField2.text floatValue]);
        [_tableView reloadData];
    }];
    
    [SRTaskService updateTaskToDevie:task];
    [_textField2 resignFirstResponder];
    [_textField1 resignFirstResponder];
    
}

- (void)exitLogin
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确认退出？" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
    }
    else {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"sleep"];
        [Utils deleteUserLoginToken:[SRMe currentUser]];
        [self.navigationController dismissViewControllerAnimated:NO completion:nil];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_arr[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIbentify = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIbentify];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIbentify];
    }
    cell.textLabel.text = _arr[indexPath.section][indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (indexPath.row == 0 && indexPath.section == 0) {
        
        SRDevice * device = [SRMe currentUser].device;
        
        if (device) {
            cell.detailTextLabel.text = NSLocalizedString(@"已绑定", nil);
        }else
            cell.detailTextLabel.text = NSLocalizedString(@"未绑定", nil);
    }
    else if (indexPath.row == 1 && indexPath.section == 0) {
        
        SRCurrentTask * task = [SRCurrentTask findCurrentTaskCINEForMe:[SRMe currentUser]];
        
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@",task.target,NSLocalizedString(@"步", nil)];
        [self calValues:[NSString stringWithFormat:@"%@",task.target]];
    }
    
    
    // 来电提醒Cell
    if (indexPath.row == 0 &&indexPath.section == 1) {
//        NSLog(@"含有开关Cell的子视图个数为%ld",cell.subviews.count);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (cell.subviews.count<=2) {
            UISwitch *switchOfCallIn = [[UISwitch alloc]init];
            switchOfCallIn.on = YES;
            switchOfCallIn.center = CGPointMake(cell.contentView.bounds.size.width-switchOfCallIn.bounds.size.width/3*2, cell.contentView.bounds.size.height/2);
            [cell.contentView addSubview:switchOfCallIn];
        }
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    // 久坐提醒Cell
    else if (indexPath.row == 1 && indexPath.section == 1)
    {
        cell.detailTextLabel.text = _sitTooLong;
    }
    cell.imageView.image = [UIImage imageNamed:_arr[indexPath.section][indexPath.row]];
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _arr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0 && indexPath.section == 0) {
        [self performSegueWithIdentifier:@"pushMytrunk" sender:self];
    }else if (indexPath.row == 1 && indexPath.section == 0)
    {
        SRDevice * device = [SRMe currentUser].device;
        if (!device) {
            [SVProgressHUD showErrorWithStatus:@"请先绑定手环"];
            return;
        }
        [_textField1 becomeFirstResponder];
        [_textField2 becomeFirstResponder];
    }else if (indexPath.row == 3 && indexPath.section == 1)
    {
        [self performSegueWithIdentifier:@"pushTucao" sender:self];
    }else if (indexPath.row == 4 && indexPath.section == 1)
    {
        [self performSegueWithIdentifier:@"pushAbout" sender:self];
    }else if (indexPath.row == 2 && indexPath.section == 1)
    {
        [self performSegueWithIdentifier:@"pushNaozhong" sender:self];
    }
    else if (indexPath.row == 1 && indexPath.section == 1)
    {
        [self sitTooLongOptionsAppear];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *str = [NSString stringWithFormat:@"%@%@",textField.text,string];
    [self calValues:str];
    return YES;
}

- (void)calValues:(NSString *)text
{
    float distance = [SRHelper distanceMeterWithHeightMeter:[_me.height floatValue]/100.0 steps:[text floatValue]];
    
    int kalorie = [SRHelper caloriesWithHeightMeter:(float)[_me.height floatValue] /100.0 weight:[_me.weight floatValue] steps:[text floatValue]];
    
    _label1.text = [NSString stringWithFormat:@"%.1f千米",distance];
    _label2.text = [NSString stringWithFormat:@"%d千卡",kalorie];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_textField2 resignFirstResponder];
    [_textField1 resignFirstResponder];
    return YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    [_tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
